package ua.kpi_java_training5.alekseenko.src.module2;

/**
 * Author: Aleksey Alekseenko
 * Date: 05.06.13
 */
public class GodsWill {
    Aquarium aquarium;

    public GodsWill() {
        this.aquarium = new Aquarium(Initialization.getLengthAquarium(), Initialization.getHeightAquarium());
    }

    /**
     * Moves all Victims, after that Predators
     */
    protected void moveAllFishes() {
        for (int index = 0; index < aquarium.fishFactory.victims.size(); index++) {
            aquarium.fishFactory.victims.get(index).move(Initialization.getStepToVictim());
        }
        for (int index = 0; index < aquarium.fishFactory.predators.size(); index++) {
            aquarium.fishFactory.predators.get(index).move(Initialization.getStepToPredator());
        }
    }

    /**
     * Set isDead Victims
     */
    protected void death() {
        do {
            removeIsDead();
            for (int index = 0; index < aquarium.fishFactory.predators.size(); index++) {
                for (int i = 0; i < aquarium.fishFactory.victims.size(); i++) {
                    if (aquarium.fishFactory.victims.get(i).position.x == aquarium.fishFactory.predators.get(index).position.x
                            && aquarium.fishFactory.victims.get(i).position.y == aquarium.fishFactory.predators.get(index).position.y) {
                        aquarium.fishFactory.victims.get(i).isDead = true;
                        Statistic.killedVictims++;
                        Initialization.numberVictims--;
                    }
                }
            }
        } while (hasIsDead());
    }

    /**
     * Checks has Victims List dead fishes
     *
     * @return
     */
    private boolean hasIsDead() {
        boolean b = false;
        for (int index = 0; index < aquarium.fishFactory.victims.size(); index++) {
            if (aquarium.fishFactory.victims.get(index).isDead) {
                b = true;
            }
        }
        return b;
    }

    /**
     * Removes dead Victims
     */
    private void removeIsDead() {
        for (int index = 0; index < aquarium.fishFactory.victims.size(); index++) {
            if (aquarium.fishFactory.victims.get(index).isDead) {
                aquarium.fishFactory.victims.remove(index);
                if (aquarium.fishFactory.victims.size() == 0) {
                    Statistic.end();
                    System.exit(0);
                }
            }
        }
    }

    protected void lifeInAquarium() {
        moveAllFishes();
        death();
    }

    /**
     * Does lifeInAquarium by set length
     *
     * @param length
     */
    protected void startLifeByLength(int length) {
        for (int i = 0; i < length; i++) {
            lifeInAquarium();
        }
    }
}
